﻿using System;
using System.Collections.Generic;
using System.Linq;
using Shell.KnowledgeBase;

namespace Shell.Nodes
{
    public class TransactionMatchNode : BranchNode
    {
        private readonly Statement _transformedInput;
        private readonly IEnumerable<Transaction> _transactions;
        private readonly Func<Transaction, int, BindingContext, Node> _next;

        public TransactionMatchNode(
            Statement transformedInput, 
            IEnumerable<Transaction> transactions,
            Func<Transaction, int, BindingContext, Node> next)
        {
            _transformedInput = transformedInput;
            _transactions = transactions;
            _next = next;
        }

        public override IEnumerable<WeightedNode> Process()
        {
            var subgoals = _transactions
                .SelectMany(
                    transaction =>
                    ContextMatchNode.Match(transaction, _transformedInput)
                                    .Where(_ => _.Item1 < (transaction.Messages.Count() - 1))
                                    .Select(_ => _next(transaction, _.Item1, _.Item2)));


            return Identity(subgoals);
        }

        public override string ToString()
        {
            return string.Format("Match Transaction: {0}", _transformedInput);
        }
    }
}